using System;
using System.Windows.Input;

namespace NoRefsTest.Client
{
	public class DelegateCommand<T> : ICommand
	{
		private readonly Func<T, bool> _canExecuteMethod;
		private readonly Action<T> _executeMethod;
		public event EventHandler CanExecuteChanged;

		public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
		{
			_executeMethod = executeMethod;
			_canExecuteMethod = canExecuteMethod;
		}

		#region ICommand Members

		public bool CanExecute(object parameter)
		{
			if (parameter == null)
			{
				var res1 = CanExecute(default(T));
				return res1;
			}
			var res = CanExecute((T) parameter);
			return res;
		}

		public void Execute(object parameter)
		{
			Execute((T) parameter);
		}

		#endregion

		public bool CanExecute(T parameter)
		{
			var res = _canExecuteMethod(parameter);
			return res;
		}

		public void Execute(T parameter)
		{
			if (!CanExecute(parameter))
			{
				throw new InvalidOperationException("Cannot execute command");
			}
			_executeMethod(parameter);
		}

		protected virtual void RaiseCanExecuteChanged()
		{
			var handler = CanExecuteChanged;
			if (handler == null) return;
			handler(this, EventArgs.Empty);
		}
	}
}